<?php
/**
 * Created by PhpStorm.
 * User: yulin
 * Date: 2018-6-22 17:19:45
 * Time:
 */

namespace app\adminapi\model;

use app\base\exception\RecordNotFoundException;
use think\Db;

class WxMiniApp extends Common
{
    /**
     * 登录
     * @param $params
     * @return $this|false|int
     * @throws RecordNotFoundException
     * @throws \think\exception\DbException
     */
    public function onLogin($params) {
        $data = [];
        $data['wx_code'] = $params['code'];
        $data['username'] = $params['username'];
        $data['password'] = $params['password'];

        $appid = 'wx24904e62cc36f197';
        $secret = '555c5ac0ec1777228c99bd6e530464f2';
//        $appid = 'wxa16a7a1358d0ea69';
//        $secret = '0bbdb0fb3f7d9bec28834aa813b491ec';

        $url = 'https://api.weixin.qq.com/sns/jscode2session?appid='.$appid.'&secret='.$secret.'&js_code='.$data['wx_code'].'&grant_type=authorization_code';
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HEADER, false);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        $wxreturn = curl_exec($ch);
        $wxreturn = json_decode($wxreturn);
        $wxreturn = get_object_vars($wxreturn);
        curl_close($ch);
        $data['session_key'] = $wxreturn['session_key'];
        $data['openid'] = $wxreturn['openid'];
        $data['unionid'] = $wxreturn['unionid'];
        $data['errcode'] = $wxreturn['errcode'];
        $data['errmsg'] = $wxreturn['errmsg'];



        if($data['openid'] && !$params['username'] && !$params['password']) {
            $user_return = Db::name('user')->where('openid', $data['openid'])->whereNull('delete_time')->find();
            $passenger_return = Db::name('passenger')->where('user_id', $user_return['user_id'])->find();
            $company_return = Db::name('company')->where('company_id', $user_return['company_id'])->find();
            if ($user_return) {
                if($user_return['state'] !== 1) {
                    $data['msg'] = '用户已被禁用#1';
                    $code = 0;
                }
                else {
                    $data['user_id'] = $user_return['user_id'];
                    $data['mobile'] = $user_return['mobile'];
                    $data['role_id'] = $user_return['role_id'];
                    $data['state'] = $user_return['state'];
                    $data['company_id'] = $user_return['company_id'];
                    $data['username'] = $user_return['username'];
                    $data['name'] = $passenger_return['name'];
                    $data['company_name'] = $company_return['company_name'];
                    $data['msg'] = '微信登录成功#1';
                    $code = 1;
                }
            }
            else{
                $data['msg'] = '该微信未绑定鹏程出行#1';
                $code = 0;
            }
        }

        elseif($params['username'] && $params['password'] && !$data['openid'] ){
            $user_return = Db::name('user')->where('username', $params['username'])->whereNull('delete_time')->find();
            if($user_return['state'] !== 1){
                $data['msg'] = '用户已被禁用#2';
                $code = 0;
            }
            elseif(!$user_return || CorePwd($params['password'],$user_return['salt']) != $user_return['password']){
                $data['msg'] = '用户名或密码错误#2';
                $code = 0;
            }
            else {
                $company_return = Db::name('company')->where('company_id', $user_return['company_id'])->find();
                $passenger_return = Db::name('passenger')->where('user_id', $user_return['user_id'])->find();
                $data['user_id'] = $user_return['user_id'];
                $data['mobile'] = $user_return['mobile'];
                $data['role_id'] = $user_return['role_id'];
                $data['state'] = $user_return['state'];
                $data['company_id'] = $user_return['company_id'];
                $data['username'] = $user_return['username'];
                $data['name'] = $passenger_return['name'];
                $data['company_name'] = $company_return['company_name'];
                $data['msg'] = '账号登录成功#2';
                $code = 1;
            }
        }

        elseif($params['username'] && $params['password'] && $data['openid']){
            $user_return = Db::name('user')->where('username', $params['username'])->whereNull('delete_time')->find();
            if($user_return['state'] !== 1){
                $data['msg'] = '用户已被禁用#3';
                $code = 0;
            }
            elseif(!$user_return || CorePwd($params['password'],$user_return['salt']) != $user_return['password']){
                $data['msg'] = '用户名或密码错误#3';
                $code = 0;
            }
            else {
                $company_return = Db::name('company')->where('company_id', $user_return['company_id'])->find();
                $passenger_return = Db::name('passenger')->where('user_id', $user_return['user_id'])->find();
                $data['user_id'] = $user_return['user_id'];
                $data['mobile'] = $user_return['mobile'];
                $data['role_id'] = $user_return['role_id'];
                $data['state'] = $user_return['state'];
                $data['company_id'] = $user_return['company_id'];
                $data['username'] = $user_return['username'];
                $data['name'] = $passenger_return['name'];
                $data['company_name'] = $company_return['company_name'];
                if($data['openid'] && $data['wx_code']) {
                    Db::name('user')->where('user_id', $data['user_id'])->update(['openid' => $data['openid']]);
                    $data['msg'] = '账号登录成功,微信绑定成功#3';
                    $code = 1;
                }
                elseif($data['wx_code']) {
                    $data['msg'] = '账号登录成功,微信绑定失败#3';
                    $code = 1;
                }
                else {
                    $data['msg'] = '账号登录成功#3';
                    $code = 1;
                }
            }
        }

        else{
            $data['msg'] = '缺少微信code,或缺少账号密码#4';
            $code = 0;
        }

        return [$code,$data];
    }

    /**
     * 修改密码
     * @param $params
     * @return $this|false|int
     * @throws RecordNotFoundException
     * @throws \think\exception\DbException
     */
    public function edit($params) {
        $data = [];
        $data['user_id'] = $params['user_id'];
        $data['password_old'] = $params['password_old'];
        $data['password_new'] = $params['password_new'];
        $user_return = Db::name('user')->where('user_id', $data['user_id'])->whereNull('delete_time')->find();
        if(!$user_return || CorePwd($data['password_old'],$user_return['salt']) != $user_return['password']){
            $data['msg'] = '旧密码错误';
            return [0,$data];
        }
        elseif($data['password_new']){
            $salt = $this->genSalt();
            $data['password_new'] = CorePwd($data['password_new'], $salt);
            Db::name('user')->where('user_id', $data['user_id'])->update(['password' => $data['password_new'],'salt' => $salt]);
            $data['msg'] = '更改密码成功';
            return [1,$data];
        }
        else{
            $data['msg'] = '登录失败,或缺少新密码';
            return [0,$data];
        }

    }

    /**
     * 解除绑定
     * @param $params
     * @return $this|false|int
     * @throws RecordNotFoundException
     * @throws \think\exception\DbException
     */
    public function deleteOpenid($params) {
        $data = [];
        $data['openid'] = $params['openid'];

        if($data['openid']) {
            $user_return = Db::name('user')->where('openid', $data['openid'])->whereNull('delete_time')->find();
            if($user_return) {
                $user_return = Db::name('user')->where('openid', $data['openid'])->update(['openid' => '']);
                if($user_return) {
                    $data['msg'] = '解绑成功';
                    return [1, $data];
                }
                else{
                    $data['msg'] = '解绑失败,请联系管理员';
                    return [0, $data];
                }
            }
            else{
                $data['msg'] = '查无此openid';
                return [0, $data];
            }
        }
        else{
            $data['msg'] = '请输入openid';
            return [0,$data];
        }
    }

    /**
     * 发送消息
     * @param $params
     * @return $this|false|int
     * @throws RecordNotFoundException
     * @throws \think\exception\DbException
     */
    public function sendMsg($params) {
        $data = [];

        $appid = 'wx24904e62cc36f197';
        $secret = '555c5ac0ec1777228c99bd6e530464f2';
        //获取access_token
        $url1 = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$appid.'&secret='.$secret;
        $ch1 = curl_init();
        curl_setopt($ch1, CURLOPT_URL, $url1);
        curl_setopt($ch1, CURLOPT_HEADER, false);
        curl_setopt($ch1, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch1, CURLOPT_SSL_VERIFYPEER, false);
        $access_tokenreturn = curl_exec($ch1);
        $access_tokenreturn = json_decode($access_tokenreturn);
        $access_tokenreturn = get_object_vars($access_tokenreturn);
        curl_close($ch1);
        $access_token = $access_tokenreturn['access_token'];

        //访问发送模板消息的API
        $params['touser'] && $post_data['touser'] = $params['touser'];
        $params['template_id'] && $post_data['template_id'] = $params['template_id'];
        $params['page'] && $post_data['page'] = $params['page'];
        $params['form_id'] && $post_data['form_id'] = $params['form_id'];
        $params['emphasis_keyword'] && $post_data['emphasis_keyword'] = $params['emphasis_keyword'];
        $params['keyword1'] && $post_data['data']['keyword1']['value'] = $params['keyword1'];
        $params['keyword2'] && $post_data['data']['keyword2']['value'] = $params['keyword2'];
        $params['keyword3'] && $post_data['data']['keyword3']['value'] = $params['keyword3'];
        $params['keyword4'] && $post_data['data']['keyword4']['value'] = $params['keyword4'];
        $params['keyword5'] && $post_data['data']['keyword5']['value'] = $params['keyword5'];
        $params['keyword6'] && $post_data['data']['keyword6']['value'] = $params['keyword6'];
        $params['keyword7'] && $post_data['data']['keyword7']['value'] = $params['keyword7'];
        $params['keyword8'] && $post_data['data']['keyword8']['value'] = $params['keyword8'];
        $params['keyword9'] && $post_data['data']['keyword9']['value'] = $params['keyword9'];
        $params['keyword10'] && $post_data['data']['keyword10']['value'] = $params['keyword10'];
        $post_data = json_encode($post_data);

        $url2 = 'https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token='.$access_token;
        $ch2 = curl_init();
        curl_setopt($ch2, CURLOPT_URL, $url2);
        curl_setopt($ch2, CURLOPT_HEADER, false);
        curl_setopt($ch2, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch2, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch2, CURLOPT_POST, 1);
        curl_setopt($ch2, CURLOPT_POSTFIELDS, $post_data);
        $wxreturn = curl_exec($ch2);
        $wxreturn = json_decode($wxreturn);
        $wxreturn = get_object_vars($wxreturn);
        curl_close($ch2);

        $data['errcode'] = $wxreturn['errcode'];
        $data['errmsg'] = $wxreturn['errmsg'];
        if($data['errcode'] == 0){
            $data['msg'] = '发送成功';
            return [1,$data];
        }
        else{
            $data['msg'] = '发送失败';
            if($data['errcode'] == 40003){
                $data['msg'] = '不合法的 OpenID，请开发者确认OpenID否是其他小程序的 OpenID';
            }
            if($data['errcode'] == 40037){
                $data['msg'] = 'template_id不正确';
            }
            if($data['errcode'] == 41028){
                $data['msg'] = 'form_id不正确，或者过期';
            }
            if($data['errcode'] == 41029){
                $data['msg'] = 'form_id已被使用';
            }
            if($data['errcode'] == 41030){
                $data['msg'] = 'page不正确';
            }
            if($data['errcode'] == 45009){
                $data['msg'] = '接口调用超过限额（目前默认每个帐号日调用限额为100万）';
            }
            return [0,$data];
        }
    }

    /**
     * 改变订单状态
     * @param $params
     * @return $this|false|int
     * @throws RecordNotFoundException
     * @throws \think\exception\DbException
     */
    public function changeOrderState($params) {
        $data = [];
        $data['order_id'] = $params['order_id'];
        $data['order_state'] = $params['order_state'];
        $data['approval_id'] = 0;
        $data['approval_id'] = $params['approval_id'];
        if($data['order_id'] && $data['order_state'] == '3'){
            Db::name('order')->where('order_id', $data['order_id'])->update(['order_state' => $data['order_state']]);
            $data['msg'] = '订单状态更改为:已拒绝';
            return [1,$data];
        }
        elseif($data['order_id'] && $data['order_state'] == '1' && $data['approval_id'] > 0){
            $passenger_return = Db::name('passenger')->where('passenger_id', $data['approval_id'])->where('is_check', 1)->whereNull('delete_time')->find();
            if($passenger_return) {
                Db::name('order')->where('order_id', $data['order_id'])->where('order_state', $data['order_state'])->update(['approval_id' => $passenger_return['passenger_id'],'approval' => $passenger_return['name']]);
                $data['msg'] = '审核员更改更改为:'.$passenger_return['name'];
                return [1,$data];
            }
            else{
                $data['msg'] = '不存在该审核人,或者该用户不具有审核权限';
                return [0,$data];
            }
        }
        else{
            $data['msg'] = '未知错误,请联系管理员';
            return [0,$data];
        }
    }

    /**
     * 生成盐
     * @return bool|string
     */
    protected function genSalt(){
        return substr(uniqid(), -6);
    }
}